import qiniu
from qiniu import Auth, put_file

# 图片处理接口
class ImageProcessor:
    def __init__(self):
        self.access_key = 'Yt8SCmWiFs3JSMC_gMHUuzWy83z4LqZ1nkyjQ4CR'
        self.secret_key = 'hMELle_fxj7wVen3Qa18NbUiyA4pwpA-yG1EIS3z'
        self.bucket_name = 'a1-21'
        
    def process_image(self, local_file_path, image_key, mode, width=None, height=None):

        raise NotImplementedError("子类必须实现抽象方法")


# 七牛云图片处理器实现
class QiniuImageProcessor(ImageProcessor):
    def __init__(self):
        self.access_key = 'Yt8SCmWiFs3JSMC_gMHUuzWy83z4LqZ1nkyjQ4CR'
        self.secret_key = 'hMELle_fxj7wVen3Qa18NbUiyA4pwpA-yG1EIS3z'
        self.bucket_name = 'a1-21'
        self.q = Auth(self.access_key, self.secret_key)

    def upload_image(self, local_file_path, image_key):
        token = self.q.upload_token(self.bucket_name, key=image_key, expires=3600)
        ret, info = put_file(token, image_key, local_file_path)
        if info.status_code != 200:
            raise Exception(f"Upload failed: {info.status_code}")
        return f"http://{self.bucket_name}.qiniudn.com/{image_key}"

    def process_image(self, local_file_path, image_key, mode, width=None, height=None):
        url = self.upload_image(local_file_path, image_key)
        params = f"/{mode}"
        if width:
            params += f"/w/{width}"
        if height:
            params += f"/h/{height}"
        return f"{url}?imageView2{params}"

# 工厂类
class ImageProcessorFactory:
    @staticmethod
    def get_image_processor(provider, access_key, secret_key, bucket_name):
        if provider == "qiniu":
            return QiniuImageProcessor(access_key, secret_key, bucket_name)
        else:   
            raise ValueError("不支持的图像处理器提供者")
